package collections4;
import java.io.*;
import java.util.*;
public class Xiancheng extends Thread {
	Map<String, Student> map = null;
	ObjectInputStream ois = null;
	ObjectOutputStream obi = null;
	String objPath = "d:/1.txt";
    
	// 读文件
	public void readMessage() {
		try {
			ois = new ObjectInputStream(new FileInputStream(objPath));
			map = (HashMap) ois.readObject();
		} catch (Exception e) {
			map = new HashMap<String, Student>();
		} finally {
			if (ois != null) {
				try {
					ois.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	// 写文件
	public void save() {
		try {
			obi = new ObjectOutputStream(new FileOutputStream(objPath));
			obi.writeObject(map);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (obi != null) {
				try {
					obi.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public void showAll() {
		Set<String> keys = map.keySet();
		java.util.Iterator<String> it = keys.iterator();
		while (it.hasNext()) {
			String key = (String) it.next();
			Student s = (Student) map.get(key);
			
		}
	}
	


	public void addStu(String stuNo, String name, String age, String stuCard) {
		Student stu = map.get(stuNo);
		if (stu == null) {
			stu = new Student(stuNo, name, age, stuCard);
			map.put(stuNo, stu);
		} else {
			System.out.println("该学号对应的学生已存在！");
		}
	}


	public boolean reviseStu(String stuNo) {
		Scanner sc = new Scanner(System.in);
		Student stu = map.get(stuNo);
		if (stu != null) {
			System.out.println("请修改学生姓名：");
			String name = sc.nextLine();
			if (name.length() != 0)
				stu.setName(name);
			System.out.println("请修改学生年龄：");
			String age = sc.nextLine();
			if (age.length() != 0)
				stu.setAge(age);
			System.out.println("请修改学生身份证号码：");
			String stuCard = sc.nextLine();
			if (stuCard.length() != 0)
				stu.setCard(stuCard);
			this.addStu(stuNo, name, age, stuCard);
			return true;
		}
		return false;
	}

	public boolean delStu(String stuNo) {
		Student stu = map.get(stuNo);
		if (stu != null) {
			map.remove(stuNo);
			return true;
		}
		return false;
	}

	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep(2000);
				//System.out.println("123");
				this.save();
			} catch (InterruptedException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}
	}
}